// ==UserScript==
// @name          TalkwithWallace.uc.js
// @description   TalkwithWallace 科学上网，和美国网友谈笑风生
// @author         Runningcheese
// @namespace   http://www.runningcheese.com
// @include        main
// @license         MIT License
// @compatibility  Firefox 29+
// @charset        UTF-8
// @version        v2017.04.09
// @version        v2017.04.02
// @version        v2016.12.11 
// @homepage    http://www.runningcheese.com/firefox-v8
// ==/UserScript==

//载入脚本
function jsonToDOM(json, doc, nodes) {

    var namespaces = {
        html: 'http://www.w3.org/1999/xhtml',
        xul: 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'
    };
    var defaultNamespace = namespaces.html;

    function namespace(name) {
        var m = /^(?:(.*):)?(.*)$/.exec(name);        
        return [namespaces[m[1]], m[2]];
    }

    function tag(name, attr) {
        if (Array.isArray(name)) {
            var frag = doc.createDocumentFragment();
            Array.forEach(arguments, function (arg) {
                if (!Array.isArray(arg[0]))
                    frag.appendChild(tag.apply(null, arg));
                else
                    arg.forEach(function (arg) {
                        frag.appendChild(tag.apply(null, arg));
                    });
            });
            return frag;
        }

        var args = Array.slice(arguments, 2);
        var vals = namespace(name);
        var elem = doc.createElementNS(vals[0] || defaultNamespace, vals[1]);

        for (var key in attr) {
            var val = attr[key];
            if (nodes && key == 'id')
                nodes[val] = elem;

            vals = namespace(key);
            if (typeof val == 'function')
                elem.addEventListener(key.replace(/^on/, ''), val, false);
            else
                elem.setAttributeNS(vals[0] || '', vals[1], val);
        }
        args.forEach(function(e) {
            try {
                elem.appendChild(
                                    Object.prototype.toString.call(e) == '[object Array]'
                                    ?
                                        tag.apply(null, e)
                                    :
                                        e instanceof doc.defaultView.Node
                                        ?
                                            e
                                        :
                                            doc.createTextNode(e)
                                );
            } catch (ex) {
                elem.appendChild(doc.createTextNode(ex));
            }
        });
        return elem;
    }
    return tag.apply(null, json);
}


//定义按钮
CustomizableUI.createWidget({
    id: 'TalkwithWallace',
    defaultArea: CustomizableUI.AREA_NAVBAR,
    label: '谈笑风生',
    tooltiptext: '科学上网，和美国网友谈笑风生',
    onCreated: function(aNode) {
    aNode.setAttribute('type', 'menu');    

        
 //定义菜单      
        var myMenuJson = 
                                ['xul:menupopup', {id: 'TalkwithWallace_pop'},
                                ['xul:menuitem', {label: 'Hosts 更新',oncommand: 'HostsUpdate();',class:'menuitem-iconic', image:''}],
                                ['xul:menuitem', {label: 'Hosts 编辑',oncommand: 'HostsEdit();',class:'menuitem-iconic', image:''}],
                                ['xul:menuitem', {label: 'Hosts 位置',oncommand: 'HostsFolder();',class:'menuitem-iconic', image:''}],
                                ['xul:menuitem', {label: 'DNS 设置',oncommand: 'SetDNS();',class:'menuitem-iconic', image:''}],
                               ['xul:menuitem', {label: 'SS一键使用',oncommand: 'RunShadowsocks();RunSSUpdateHK();',class:'menuitem-iconic', image:''}],
                               ['xul:menuitem', {label: 'SS程序启动',oncommand: 'RunShadowsocks();',class:'menuitem-iconic', image:''}],
                               ['xul:menuitem', {label: 'SS备用帐号',oncommand: 'RunSSUpdate();',tooltiptext: '每12小时更新一次，速度快',class:'menuitem-iconic', image:''}],
                               ['xul:menuitem', {label: 'SS备用二维码',oncommand: 'var x = gBrowser.mCurrentTab._tPos + 1; gBrowser.moveTabTo(gBrowser.selectedTab =gBrowser.addTab("http://ss8.pm/images/server02.png"), x);',class:'menuitem-iconic', image:''}],
                               //['xul:menuitem', {label: 'GoAgent',oncommand: 'RunGoAgent();',class:'menuitem-iconic', image:''}],
                                ['xul:menuseparator', {}],
                                ['xul:menuitem', {label: '如何使用？',oncommand: 'var x = gBrowser.mCurrentTab._tPos + 1; gBrowser.moveTabTo(gBrowser.selectedTab =gBrowser.addTab("https://github.com/runningcheese/cheesehosts/wiki/how-to-use"), x);',class:'menuitem-iconic', image:''}]
                        ];
        aNode.appendChild(jsonToDOM(myMenuJson, aNode.ownerDocument, {}));
        aNode.setAttribute('menupopup', 'TalkwithWallace_pop');
    }
});


//定义图标
var cssStr = '@-moz-document url("chrome://browser/content/browser.xul"){'
		 + '#TalkwithWallace[cui-areatype="toolbar"] .toolbarbutton-icon {'
		 + 'list-style-image:url()'
		 + '}}'
     + '#TalkwithWallace[cui-areatype="menu-panel"] .toolbarbutton-icon, toolbarpaletteitem[place="palette"]> #TalkwithWallace .toolbarbutton-icon {'
		 + 'list-style-image:url()'
		 + '}}';
	var sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
	var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
	sss.loadAndRegisterSheet(ios.newURI("data:text/css;base64," + btoa(cssStr), null, null), sss.USER_SHEET);




//定义函数
function	HostsUpdate() {
gBrowser.mPrefs.setCharPref("extensions.autoproxy.proxyMode","disabled");
var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\HostsUpdate.bat"); file.launch(); return file;
};


function	HostsEdit() { 
gBrowser.mPrefs.setCharPref("extensions.autoproxy.proxyMode","disabled"); 
var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\HostsEdit.bat"); file.launch(); return file;
};

				
function	HostsFolder() {
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("SysD", Components.interfaces.nsILocalFile).path + "\\drivers\\etc");
file.launch(); return file;
};


function	SetDNS() { 
gBrowser.mPrefs.setCharPref("extensions.autoproxy.proxyMode","disabled");
var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\DnsJumper.exe"); file.launch(); return file;
};


function	RunShadowsocks() { 
gBrowser.mPrefs.setCharPref("extensions.autoproxy.proxyMode","auto");
gBrowser.mPrefs.setIntPref("extensions.autoproxy.default_proxy",1);
var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\Shadowsocks\\ShadowsocksR.exe"); file.launch(); return file;
};


function	RunSSUpdate() { var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\Shadowsocks\\shadowsocks8.exe"); file.launch(); return file;};


function	RunSSUpdateHK() { var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\Shadowsocks\\shadowsocks8-HK.exe"); file.launch(); return file;};


function	RunGoAgent() { 
gBrowser.mPrefs.setCharPref("extensions.autoproxy.proxyMode","auto");
gBrowser.mPrefs.setIntPref("extensions.autoproxy.default_proxy",0);
var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile); file.appendRelativePath("Local\\XX-Net\\start.vbs"); file.launch(); return file;
};